<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
  <title>Pivot.js</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <!-- Twitter Bootstrap -->
  <link rel="stylesheet" href="./lib/css/bootstrap.min.css" type="text/css" />
  <link rel="stylesheet" href="./lib/css/subnav.css" type="text/css" />
  <link rel="stylesheet" href="./lib/css/pivot.css" type="text/css" />

  <script type="text/javascript" src="./lib/javascripts/jquery.min.js"></script>
  <script type="text/javascript" src="./lib/javascripts/subnav.js"></script>
  <script type="text/javascript" src="./lib/javascripts/accounting.min.js"></script>
  <script type="text/javascript" src="./lib/javascripts/jquery.dataTables.min.js"></script>
  <script type="text/javascript" src="./lib/javascripts/dataTables.bootstrap.js"></script>

  <script type="text/javascript">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-42535149-1', 'rjackson.github.io');
    ga('send', 'pageview');
  </script>

  <!-- jquery_pivot must be loaded after pivot.js and jQuery -->
  <script type="text/javascript" src="./pivot.js"></script>
  <script type="text/javascript" src="./jquery_pivot.js"></script>
</head>
<body>

  <div class="container">
  
    <div class="subnav">
      <ul class="nav nav-pills">
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            Filter Fields
            <b class="caret"></b>
          </a>
          <ul class="dropdown-menu stop-propagation" style="overflow:auto;max-height:450px;padding:10px;">
            <div id="filter-list"></div>
          </ul>
        </li>
		
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            Column Label Fields
            <b class="caret"></b>
          </a>
          <ul class="dropdown-menu stop-propagation" style="overflow:auto;max-height:450px;padding:10px;">
            <div id="column-label-fields"></div>
          </ul>
        </li>
        <li class="dropdown pull-right">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            Row Label Fields
            <b class="caret"></b>
          </a>
          <ul class="dropdown-menu stop-propagation" style="overflow:auto;max-height:450px;padding:10px;">
            <div id="row-label-fields"></div>
          </ul>
        </li>
        <li class="dropdown pull-right">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            Summary Fields
            <b class="caret"></b>
          </a>
          <ul class="dropdown-menu stop-propagation" style="overflow:auto;max-height:450px;padding:10px;">
            <div id="summary-fields"></div>
          </ul>
        </li>
		<!--
        <li class="dropdown pull-right">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            Canned Reports
            <b class="caret"></b>
          </a>
          <ul class="dropdown-menu">
           <li><a id="ar-aged-balance" href="#">AR Aged Balance</a></li>
           <li><a id="acme-detail-report" href="#">Acme Corp Detail</a></li>
           <li><a id="miami-invoice-detail" href="#">Miami Invoice Detail</a></li>
          </ul>
        </li>
		-->
      </ul>
    </div>
    <hr/>
	
    <div id="results"></div>
  </div>
</body>

<script type="text/javascript">

function ageBucket(row, field){
  var age = Math.abs(((new Date().getTime()) - row[field.dataSource])/1000/60/60/24);
  switch (true){
    case (age < 31):
      return '000 - 030'
    case (age < 61):
      return '031 - 060'
    case (age < 91):
      return '061 - 090'
    case (age < 121):
      return '091 - 120'
    default:
      return '121+'
  }
};

// Define the structure of fields, if this is not defined then all fields will be assumed
// to be strings.  Name must match csv header row (which must exist) in order to parse correctly.
var fields = [
    // filterable fields
    {name: 'last_name',         type: 'string', filterable: true, filterType: 'regexp'},
    {name: 'first_name',        type: 'string', filterable: true},
    {name: 'state',             type: 'string', filterable: true},
    {name: 'employer',          type: 'string', filterable: true,  filterType: 'regexp',dataSource: 'employer'},
    {name: 'city',              type: 'string', filterable: true},
    {name: 'invoice_date',      type: 'date',   filterable: true},

    // psuedo fields
	{
		name: 'Nhân viên', type: 'string', filterable: true, columnLabelable: true, 
		pseudo: true,
		pseudoFunction: function(row){ return row.employer }
	},
    {name: 'invoice_mm', type: 'string', filterable: true, pseudo: true,
      pseudoFunction: function(row){
          var date = new Date(row.invoice_date);
          return pivot.utils().padLeft((date.getMonth() + 1),2,'0')}
    },
    {name: 'invoice_yyyy_mm', type: 'string', filterable: true, pseudo: true,
      pseudoFunction: function(row){
        var date = new Date(row.invoice_date);
        return date.getFullYear() + '_' + pivot.utils().padLeft((date.getMonth() + 1),2,'0')}
    },
    {name: 'Tổng năm', type: 'string', filterable: true, pseudo: true, columnLabelable: true,
      pseudoFunction: function(row){ return "Năm " + new Date(row.invoice_date).getFullYear() }},
    {
		name: 'age_bucket', type: 'string', filterable: true, columnLabelable: true, 
		pseudo: true, dataSource: 'last_payment_date', pseudoFunction: ageBucket
	},
    {
		name: 'total', type: 'string', filterable: true, columnLabelable: true, 
		pseudo: true, dataSource: 'employer', 
		pseudoFunction: function(row){ return "Tổng cộng" }
	},


    // summary fields
    {name: 'billed_amount',     type: 'float',  rowLabelable: false, summarizable: 'sum', displayFunction: function(value){ return accounting.formatMoney(value)}},
    {name: 'payment_amount',    type: 'float',  rowLabelable: false, summarizable: 'sum', displayFunction: function(value){ return accounting.formatMoney(value)}},
    {
		name: 'balance', type: 'float', rowLabelable: false, pseudo: true,
		pseudoFunction: function(row){ return row.billed_amount - row.payment_amount },
		summarizable: 'sum', displayFunction: function(value){ return accounting.formatMoney(value)}
	},
    {name: 'last_payment_date',  type: 'date',  filterable: true}
]

  function setupPivot(input){
    input.callbacks = {afterUpdateResults: function(){
      $('#results > table').dataTable({
        "sDom": "<'row'<'span6'l><'span6'f>>t<'row'<'span6'i><'span6'p>>",
        "iDisplayLength": 20,
        "aLengthMenu": [[200, 50, 100, -1], [20, 50, 100, "All"]],
        "sPaginationType": "bootstrap",
        "oLanguage": {
          "sLengthMenu": "_MENU_ records per page"
        }
      });
    }};
    $('#pivot-demo').pivot_display('setup', input);
  };

  $(document).ready(function() {

    setupPivot({
		url:'./lib/csv/demo.csv', 
		fields: fields, 
		//filters: {employer: 'Acme Corp'}, 
		rowLabels:[
			//"last_name",
			//"first_name",
			//"Nhân viên",
			"city"
		],
		columnLabels:[
			//"city",
			"Tổng năm",
			"total"
		], 
		summaries:[
			//"invoice_yyyy_mm",
			//"billed_amount", 
			//"payment_amount", 
			"balance"
		]
	});
	
	
    // prevent dropdown from closing after selection
    $('.stop-propagation').click(function(event){
      event.stopPropagation();
    });

  });
</script>
